import json
import re
from pprint import pprint

import requests
from bs4 import BeautifulSoup


class Spider:

    def __init__(self):
        self.getHtmlHeaders = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            # 'Accept-Encoding': 'gzip, deflate, br',
            'Origin': 'https://www.bilibili.com',
            'Referer': 'https://www.bilibili.com',
            'Accept-Language': 'zh-CN,zh;q = 0.9'
        }
        self.downloadVideoHeaders = {
            'Origin': 'https://www.bilibili.com',
            'Referer': 'https://www.bilibili.com',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        }

    def getList(self):
        r = requests.get(
            'https://api.bilibili.com/x/v3/fav/resource/list?media_id=159078549&pn=1&ps=20&keyword=&order=mtime&type=0&tid=0&platform=web&jsonp=jsonp',
            headers=self.getHtmlHeaders).text
        rJson = json.loads(r)
        return rJson['data']['medias']

    def audioUrl(self, url):
        r = requests.get(url, headers=self.getHtmlHeaders).text
        soup = BeautifulSoup(r, 'lxml')
        title = soup.select('#viewbox_report > h1 > span')[0].text
        pattern = r'\<script\>window\.__playinfo__=(.*?)\</script\>'
        result = re.findall(pattern, r)[0]
        temp = json.loads(result)
        # print(temp['data']['dash']['video'])
        audioUrl = temp['data']['dash']['audio'][0]['backupUrl'][0]
        return audioUrl
        # for item in temp['data']['video']:
        #     if 'url' in item.keys():
        #         video_url = item['url']
        # print(video_url)
        # print(title)
        # title = re.sub(r'[/:*?"<>|]', '-', title)  # 去掉创建文件时的非法字符
        # url = 'https://upos-sz-mirrorkodo.bilivideo.com/upgcxcode/12/26/312892612/312892612_nb2-1-30080.m4s?e=ig8euxZM2rNcNbdlhoNvNC8BqJIzNbfqXBvEqxTEto8BTrNvN0GvT90W5JZMkX_YN0MvXg8gNEV4NC8xNEV4N03eN0B5tZlqNxTEto8BTrNvNeZVuJ10Kj_g2UB02J0mN0B5tZlqNCNEto8BTrNvNC7MTX502C8f2jmMQJ6mqF2fka1mqx6gqj0eN0B599M=&uipk=5&nbs=1&deadline=1618116421&gen=playurlv2&os=kodobv&oi=2869625310&trid=0c9dc64b66594e2c8079b4bb98f10687u&platform=pc&upsig=885f2071a326316fa7975d7e5122ce22&uparams=e, uipk, nbs, deadline, gen, os, oi, trid, platform&mid=0&orderid=0, 3&agrr=1&logo=80000000'
        # filename = title + '.mp3'
        # requests.packages.urllib3.disable_warnings()
        # with open(filename, "wb") as f:
        #     f.write(requests.get(url=audioUrl, headers=self.downloadVideoHeaders, stream=True,
        #                          verify=False).content)

    def download(self, title, url):
        title = re.sub(r'[/:*?"<>|]', '-', title)  # 去掉创建文件时的非法字符
        filename = title + '.m4a'
        requests.packages.urllib3.disable_warnings()
        with open(filename, "wb") as f:
            f.write(requests.get(url=url, headers=self.downloadVideoHeaders, stream=True,
                                 verify=False).content)


if __name__ == '__main__':
    spider = Spider()
    vMsg = spider.getList()[0]
    pprint(vMsg)
    # spider.vedio('https://www.bilibili.com/video/' + vMsg['bvid'])
